package watercalc;

import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Parser {

	static Graph parse(String iFilename) {

		Scanner scanner = null;
		File inputFile = null;
		int[] header;
		Graph container = null;
		
		try {
			inputFile = new File(iFilename);
			scanner = new Scanner(inputFile);
			header = parseHeader(scanner);
			container = parseData(scanner, header[0], header[1]);
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
			exitWrongInputFile();
		} finally {
            if (scanner != null) {
            	scanner.close();
            }
        }

		return container;
	}

	static int[] parseHeader(Scanner iScanner) {

		int[] header = {0, 0};
		
		if (iScanner.hasNextInt()) {
			header[0] = iScanner.nextInt();
		} else {
			System.out.println("Error reading input file:");
			exitWrongInputFile();
		}

		if (iScanner.hasNextInt()) {
			header[1] = iScanner.nextInt();
		} else {
			System.out.println("Error reading input file:");
			exitWrongInputFile();
		}
		
		if (header[0] == 0 || header[1] == 0) {
			System.out.println("Error reading input file:");
			System.out.println("Wrong header, need to specify number of rows and columns as positive integers.");
			exitWrongInputFile();
		}

		System.out.println("Parsed header: expecting " + header[0] + " rows and " + header[1] + " columns.");
		return header;
	}

	static Graph parseData(Scanner iScanner, int iRows, int iColumns) {

		ArrayList<Vertex> vertexes = new ArrayList<Vertex>();

		vertexes.ensureCapacity(iRows * iColumns);
		
		int currentRow = 0, currentColumn = 0;
	
		while (iScanner.hasNextInt()) {
			vertexes.add(new Vertex(iScanner.nextInt()));
			currentColumn++;
			currentColumn %= iColumns;
			if (currentColumn == 0) {
				currentRow++;
			}
		}

		if (iScanner.hasNext()) {
			System.out.println("Error reading input file at row " + (currentRow+1) + ", column " + (currentColumn+1));
			exitWrongInputFile();
		}

		if (vertexes.size() != iRows * iColumns ) {
			System.out.println("Error reading input file: expecting " + (iRows*iColumns) + " elements, but found " + vertexes.size());
			exitWrongInputFile();
		}

		System.out.println("Parsed data without errors.");

		return new Graph(iRows, iColumns, vertexes);
	}

	static void exitWrongInputFile() {
		System.out.println("Expected input file format:");
		System.out.println();
		System.out.println("rows columns");
		System.out.println("element(0,0)\t...\telement(0,columns)");
		System.out.println("...\t\t...\t...");
		System.out.println("element(rows,0)\t...\telement(rows,columns)");
		System.exit(WaterCalc.EXIT_FAILURE);
	}
	
}
